﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace VAsensorTest
{
    public partial class FormMain : Form
    {
        private VAsensor vAsensor;
        public FormMain()
        {
            InitializeComponent();
            Logger.Callback_ShowMessage = new delegate_ShowMessageToTextBox(AddToTextBoxMsg);
            
            vAsensor = new VAsensor(serialPort1, "COM1", "115200", "NONE", this);
        }

        #region 定义了一堆的委托
        public delegate void delegate_ShowMessageToTextBox(string msg);
        private void AddToTextBoxMsg(String s)
        {
            try
            {
                if (textBox_Message != null && !textBox_Message.IsDisposed)
                {
                    if (textBox_Message.InvokeRequired)
                    {
                        delegate_ShowMessageToTextBox d = AddToTextBoxMsg;
                        textBox_Message.Invoke(d, s);
                    }
                    else
                    {
                        if (textBox_Message.Lines.GetUpperBound(0) >= 1000)
                        {
                            textBox_Message.Text = s;
                        }
                        else
                        {
                            textBox_Message.AppendText(s);
                        }
                    }
                }
            }
            catch (Exception unerr) { Console.WriteLine(unerr); }
        }
        
        //定义一个委托，用于TextBox和Label的text属性修改
        public delegate void delegate_RefreshUI(Control c, Object o);
        public void refreshLabel(Control c, Object o)
        {
            try
            {
                ((Label)c).Text = o.ToString();
            }
            catch (Exception unerr) { Logger.WriteLog(unerr.ToString()); }
        }
        public void refreshTextBox(Control c, Object o)
        {
            try
            {
                ((TextBox)c).Text = o.ToString();
            }
            catch (Exception unerr) { Logger.WriteLog(unerr.ToString()); }
        }
        public void refreshButton(Control c, Object o)
        {
            try
            {
                ((Button)c).Text = o.ToString();
            }
            catch (Exception unerr) { Logger.WriteLog(unerr.ToString()); }
        }
        #endregion

        private void FormMain_Shown(object sender, EventArgs e)
        {
            string[] ArryPort = System.IO.Ports.SerialPort.GetPortNames();
            comboBox_ComNum.Items.Clear();
            if (ArryPort.Length > 0)
            {
                for (int i = 0; i < ArryPort.Length; i++)
                {
                    comboBox_ComNum.Items.Add(ArryPort[i]);
                }
                comboBox_ComNum.SelectedIndex = 0;
            }
            //comboBox_ComNum.Items.Add("COM3");
            //comboBox_ComNum.Items.Add("COM2");
            //comboBox_ComNum.Items.Add("COM1");
            
            comboBox_BaudRate.Items.Clear();
            comboBox_BaudRate.Items.Add("38400（默认）");
            comboBox_BaudRate.Items.Add("115200");
            comboBox_BaudRate.Items.Add("9600");
            comboBox_BaudRate.SelectedIndex = 0;
        }
        //this.Invoke(new delegate_RefreshUI(refreshTextBox), new object[] { textBox_V_Param1, textBox_V_Param1.Text });
        //this.Invoke(new delegate_RefreshUI(refreshLabel), new object[] { label_V_Data, "+9999.00V" });

        #region 给panel绘制了一个彩色边框
        /// <summary>
        /// 给panel绘制了一个彩色边框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void splitContainer3_Panel2_Paint(object sender, PaintEventArgs e)
        {
            ControlPaint.DrawBorder(e.Graphics,
                this.splitContainer3.Panel2.ClientRectangle,
                Color.ForestGreen, 2, ButtonBorderStyle.Solid,
                Color.ForestGreen, 2, ButtonBorderStyle.Solid,
                Color.ForestGreen, 2, ButtonBorderStyle.Solid,
                Color.ForestGreen, 2, ButtonBorderStyle.Solid);
        }

        /// <summary>
        /// 给panel绘制了一个彩色边框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void splitContainer3_Panel1_Paint(object sender, PaintEventArgs e)
        {
            ControlPaint.DrawBorder(e.Graphics,
                this.splitContainer3.Panel1.ClientRectangle,
                Color.DarkRed, 2, ButtonBorderStyle.Solid,
                Color.DarkRed, 2, ButtonBorderStyle.Solid, 
                Color.DarkRed, 2, ButtonBorderStyle.Solid, 
                Color.DarkRed, 2, ButtonBorderStyle.Solid);
        }
        #endregion

        #region 一堆的按钮处理事件，用于发送串口指令数据

        /// <summary>
        /// 打开串口 按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_OpenCom_Click(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen)//判断串口是否已经被打开了
            {
                vAsensor.CloseCom();
            }
            else
            {
                vAsensor.ComNameStr = comboBox_ComNum.Text;
                string baudrate_str = "";
                if (comboBox_BaudRate.Text.IndexOf("（默认）") >= 0)
                {
                    //将字符串中的"（默认）"字符删除，提取波特率数字38400
                    baudrate_str = comboBox_BaudRate.Text.Substring(0, comboBox_BaudRate.Text.Length - "（默认）".Length);
                }
                else
                {
                    baudrate_str = comboBox_BaudRate.Text;
                }
                vAsensor.BaudRateStr = baudrate_str;
                vAsensor.OpenCom();
            }
            if (!serialPort1.IsOpen)
            {
                button_OpenCom.Text = "打开串口(已关闭)";
                button_OpenCom.ForeColor = Color.Red;
                button_GetAdcData.Enabled = false;
                button_SetVsensorParam.Enabled = false;
                button_GetVsensorParam.Enabled = false;
                button_SetAsensorParam.Enabled = false;
                button_GetAsensorParam.Enabled = false;
                button_AutoCalibrate.Enabled = false;
                button_SetCalibrate.Enabled = false;
                button_GetCalibrate.Enabled = false;
                button_SetUploadTime.Enabled = false;
                button_GetUploadTime.Enabled = false;
                button_GetVersion.Enabled = false;
                button_Reset.Enabled = false;
            }
            else
            {
                button_OpenCom.Text = "关闭串口(已打开)";
                button_OpenCom.ForeColor = Color.Green;
                button_GetAdcData.Enabled = true;
                button_SetVsensorParam.Enabled = true;
                button_GetVsensorParam.Enabled = true;
                button_SetAsensorParam.Enabled = true;
                button_GetAsensorParam.Enabled = true;
                button_AutoCalibrate.Enabled = true;
                button_SetCalibrate.Enabled = true;
                button_GetCalibrate.Enabled = true;
                button_SetUploadTime.Enabled = true;
                button_GetUploadTime.Enabled = true;
                button_GetVersion.Enabled = true;
                button_Reset.Enabled = true;
            }
        }

        

        /// <summary>
        /// 获取采样数据 按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_GetAdcData_Click(object sender, EventArgs e)
        {
            vAsensor.GetAdcData();
        }

        private void ErrorMsg_textBox_V_Param1()
        {
            textBox_Message.AppendText("出错，电压传感器量程V，填写的不正确，请按照下面模板填写：“+-xxxx.xV”，其中字符‘x’必须为数字\r\n");
        }

        private void ErrorMsg_textBox_V_Param2()
        {
            textBox_Message.AppendText("出错，输出电压阈值V，填写的不正确，请按照下面模板填写：“+-xx.xV”，其中字符‘x’必须为数字\r\n");
        }

        /// <summary>
        /// 下载电压传感器参数 按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_SetVsensorParam_Click(object sender, EventArgs e)
        {
            string s1 = textBox_V_Param1.Text;
            string s2 = textBox_V_Param2.Text;
            if (s1.Length != 9)                                     { ErrorMsg_textBox_V_Param1(); return; }
            else if (s1.IndexOf("+-") != 0)                         { ErrorMsg_textBox_V_Param1(); return; }
            else if (s1.IndexOf("V") != 8 && s1.IndexOf("v") != 8)  { ErrorMsg_textBox_V_Param1(); return; }
            else
            {
                s1 = s1.Substring(2, 6);
                try { Convert.ToDecimal(s1); } catch                { ErrorMsg_textBox_V_Param1(); return; }
            }
            if (s2.Length != 7)                                     { ErrorMsg_textBox_V_Param2(); return; }
            else if (s2.IndexOf("+-") != 0)                         { ErrorMsg_textBox_V_Param2(); return; }
            else if (s2.IndexOf("V") != 6 && s2.IndexOf("v") != 6)  { ErrorMsg_textBox_V_Param2(); return; }
            else
            {
                s2 = s2.Substring(2, 4);
                try { Convert.ToDecimal(s2); } catch                { ErrorMsg_textBox_V_Param2(); return; }
            }
            vAsensor.SetVsensorParam(textBox_V_Param1.Text + textBox_V_Param2.Text);
        }

        /// <summary>
        /// 回读电压传感器参数 按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_GetVsensorParam_Click(object sender, EventArgs e)
        {
            vAsensor.GetVsensorParam();
        }

        private void ErrorMsg_textBox_A_Param1()
        {
            textBox_Message.AppendText("出错，电流传感器量程A，填写的不正确，请按照下面模板填写：“+-xxxx.xA”，其中字符‘x’必须为数字\r\n");
        }

        private void ErrorMsg_textBox_A_Param2()
        {
            textBox_Message.AppendText("出错，输出电压阈值V，填写的不正确，请按照下面模板填写：“+-xx.xV”，其中字符‘x’必须为数字\r\n");
        }

        /// <summary>
        /// 下载电流传感器参数 按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_SetAsensorParam_Click(object sender, EventArgs e)
        {
            string s1 = textBox_A_Param1.Text;
            string s2 = textBox_A_Param2.Text;
            if (s1.Length != 9)                                     { ErrorMsg_textBox_A_Param1(); return; }
            else if (s1.IndexOf("+-") != 0)                         { ErrorMsg_textBox_A_Param1(); return; }
            else if (s1.IndexOf("A") != 8 && s1.IndexOf("a") != 8)  { ErrorMsg_textBox_A_Param1(); return; }
            else
            {
                s1 = s1.Substring(2, 6);
                try { Convert.ToDecimal(s1); } catch                { ErrorMsg_textBox_A_Param1(); return; }
            }
            if (s2.Length != 7)                                     { ErrorMsg_textBox_A_Param2(); return; }
            else if (s2.IndexOf("+-") != 0)                         { ErrorMsg_textBox_A_Param2(); return; }
            else if (s2.IndexOf("V") != 6 && s2.IndexOf("v") != 6)  { ErrorMsg_textBox_A_Param2(); return; }
            else
            {
                s2 = s2.Substring(2, 4);
                try { Convert.ToDecimal(s2); } catch                { ErrorMsg_textBox_A_Param2(); return; }
            }
            vAsensor.SetAsensorParam(textBox_A_Param1.Text + textBox_A_Param2.Text);
        }

        /// <summary>
        /// 回读电流传感器参数 按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_GetAsensorParam_Click(object sender, EventArgs e)
        {
            vAsensor.GetAsensorParam();
        }

        /// <summary>
        /// 自动出厂零点校正 按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_AutoCalibrate_Click(object sender, EventArgs e)
        {
            vAsensor.AutoCalibrate();
        }

        /// <summary>
        /// 下载零点校正参数 按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_SetCalibrate_Click(object sender, EventArgs e)
        {
            try
            {
                int v_dat = 100;
                v_dat = Convert.ToInt32(textBox_V_ZeroData.Text);
                v_dat = System.Math.Abs(v_dat);
                int a_dat = 100;
                a_dat = Convert.ToInt32(textBox_A_ZeroData.Text);
                a_dat = System.Math.Abs(a_dat);
                vAsensor.SetCalibrate(v_dat, a_dat);
            }
            catch
            {
                textBox_Message.AppendText("出错，零点校正参数，填写的不是一个正常的数字，请填写一个小于100000000的正整数\r\n");
            }
        }

        /// <summary>
        /// 回读零点校正参数 按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_GetCalibrate_Click(object sender, EventArgs e)
        {
            vAsensor.GetCalibrate();
        }

        /// <summary>
        /// 下载主动上传间隔 按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_SetUploadTime_Click(object sender, EventArgs e)
        {           
            try
            {
                int i = 100;
                i = Convert.ToInt32(textBox_UploadTime.Text);
                i = System.Math.Abs(i);
                vAsensor.SetUploadTime(i);
            }
            catch
            {
                textBox_Message.AppendText("出错，主动上传间隔ms，填写的不是一个正常的数字，请填写一个小于1000000的正整数\r\n");
            }
        }

        /// <summary>
        /// 回读主动上传间隔 按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_GetUploadTime_Click(object sender, EventArgs e)
        {
            vAsensor.GetUploadTime();
        }

        /// <summary>
        /// 回读固件版本号 按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_GetVersion_Click(object sender, EventArgs e)
        {
            vAsensor.GetVersion();
        }

        /// <summary>
        /// 复位采集器 按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_Reset_Click(object sender, EventArgs e)
        {
            vAsensor.Reset();
        }
        
        
        #endregion

        /// <summary>
        /// 界面控件的右击菜单 点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ToolStripMenuItem_Help_1_Click(object sender, EventArgs e)
        {
            openPicture();
        }

        /// <summary>
        /// 界面控件的右击菜单 点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ToolStripMenuItem_1_Click(object sender, EventArgs e)
        {
            openPicture();
        }

        /// <summary>
        /// 界面控件的右击菜单 点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ToolStripMenuItem_2_Click(object sender, EventArgs e)
        {
            textBox_Message.Text = "";
        }

        /// <summary>
        /// 查找软件目录下的图片文件，找到则返回图片文件的完整路径和文件名称，未找到则返回""
        /// </summary>
        /// <returns></returns>
        private string findPicture()
        {
            string filePath = System.Windows.Forms.Application.StartupPath;
            string[] files;
            string[] houzhui = { "*.jpg", "*.jpeg", "*.bmp", "*.png"};
            for (int i = 0; i < houzhui.Length; i++)
            {
                files = System.IO.Directory.GetFiles(filePath, houzhui[i]);
                if (files.Length != 0)
                {
                    foreach (var file in files)
                    {
                        Console.WriteLine(file);
                        return file;
                    }
                }
            }
            return "";
        }

        /// <summary>
        /// 打开软件目录下的图片
        /// </summary>
        private void openPicture()
        {
            //string filePathName = "";//定义图像文件的位置（包括路径及文件名）
            //OpenFileDialog ofd = new OpenFileDialog(); //添加打开对话框
            //ofd.Filter = "图像文件|*jpg;*.bmp;*.png,*.tif|所有文件|*.*";  //设置过滤器
            //if (ofd.ShowDialog() == DialogResult.OK)//如果确定打开图片，则保存文件的路径及文件名到字符串变量filePathName中
            //{
            //filePathName = ofd.FileName;  //包括路径和文件名
            //}
            //else if (ofd.ShowDialog() == DialogResult.Cancel) //如果取消打开，弹出“取消打开”窗口提示
            //MessageBox.Show("取消打开");

            string filePathAndName = findPicture();
            if (filePathAndName.Length == 0)
            {
                textBox_Message.AppendText("未找到接线图\r\n");
                return;
            }

            //建立新的系统进程    
            System.Diagnostics.Process process = new System.Diagnostics.Process();

            //设置图片的真实路径和文件名    
            process.StartInfo.FileName = filePathAndName;

            //设置进程运行参数，这里以最大化窗口方法显示图片。    
            process.StartInfo.Arguments = "rundl132.exe C://WINDOWS//system32//shimgvw.dll,ImageView_Fullscreen";

            //此项为是否使用Shell执行程序，因系统默认为true，此项也可不设，但若设置必须为true    
            process.StartInfo.UseShellExecute = true;

            //此处可以更改进程所打开窗体的显示样式，可以不设    
            process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            process.Start();
            process.Close();
        }
    }
}

